package com.ken.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ken.context.BaseContext;
import com.ken.entity.AddressBook;
import com.ken.mapper.AddressBookMapper;
import com.ken.service.AddressBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements AddressBookService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBook> getCurrentUserAddressBook(AddressBook addressBook) {
        return list(new LambdaQueryWrapper<AddressBook>()
                .like(StrUtil.isNotBlank(addressBook.getPhone()), AddressBook::getPhone, addressBook.getPhone())
                .like(addressBook.getUserId() != null, AddressBook::getUserId, addressBook.getUserId())
                .like(addressBook.getIsDefault() != null, AddressBook::getIsDefault, addressBook.getIsDefault()));
    }

    @Override
    @Transactional
    public void setDefault(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        List<AddressBook> list = getCurrentUserAddressBook(addressBook);
        if (list!=null&&!list.isEmpty()) {
            for (AddressBook addressBookSetDefault : list) {
                addressBookSetDefault.setIsDefault(0);
                saveOrUpdate(addressBookSetDefault);
            }
        }
        AddressBook setDefaultAddress = getById(addressBook.getId());
        setDefaultAddress.setIsDefault(1);
        updateById(setDefaultAddress);
    }

}
